package logic

import (
	"context"
	"github.com/SpectatorNan/gorm-zero/gormc/pagex"
	"gorm.io/gorm"
	"strings"

	"go-zero-all-demos/apps/user/pb/user"
	"go-zero-all-demos/apps/user/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/jinzhu/copier"
)

type GetUserListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserListLogic {
	return &GetUserListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// GetUserList 用户列表
func (l *GetUserListLogic) GetUserList(in *user.UserListRequest) (*user.UserListResponse, error) {
	// 处理关键词为空的情况
	keyword := strings.TrimSpace(in.Keyword)
	var whereClause func(db *gorm.DB) *gorm.DB
	if keyword != "" {
		whereClause = func(db *gorm.DB) *gorm.DB {
			return db.Where("name LIKE ?", "%"+keyword+"%")
		}
	} else {
		whereClause = func(db *gorm.DB) *gorm.DB {
			return db
		}
	}

	listReq := &pagex.ListReq{
		Page:     int(in.Page),
		PageSize: int(in.PageSize),
		LastSize: int(in.LastSize),
	}
	orderBy := pagex.OrderBy{
		OrderKey: "id",
		Sort:     "descend",
	}
	orderKeys := map[string]string{"id": "id"}
	users, count, err := l.svcCtx.UserModel.FindPageList(l.ctx, listReq, orderBy, orderKeys, whereClause)
	if err != nil {
		return nil, err
	}

	userList := make([]*user.UserInfo, 0)
	for _, u := range users {
		var us user.UserInfo
		_ = copier.Copy(&us, u)
		userList = append(userList, &us)
	}
	return &user.UserListResponse{Users: userList, Total: count, Page: in.Page}, nil
}
